package com.woniu.config;

import com.woniu.exception.SecurityLoginException;
import com.woniu.mapper.UserMapper;
import com.woniu.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 去数据库中查询用户信息
 * @author tarnett
 */
@Component
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 1. 根据用户名查询用户信息
        User user = userMapper.getByAccount(account);
        // 2. 判断用户的状态
        if(user == null){
            throw new SecurityLoginException("该用户不存在");
        }
        if("0".equals(user.getStatus())){
            throw new SecurityLoginException("该用户已经被锁定了");
        }
        // 3. 查询用户具备的权限
        Set<GrantedAuthority>  auths = new HashSet<>();
        // 4. 返回用户（校验密码）
        return new org.springframework.security.core.userdetails.User(account, user.getPassword(), auths);
    }
}
